package com.sxl.controller;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.sxl.config.ExcelUtil;
import com.sxl.config.LayUiResult;
import com.sxl.config.ObjectConversion;
import com.sxl.domain.*;
import com.sxl.mapper.UsersMapper;
import com.sxl.service.StudentsService;
import com.sxl.service.UserrolesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ProjectName: CRMProject
 * @Package: com.sxl.controller
 * @Author songxueliang
 * @Date 2022/4/29 11:34
 */
@RequestMapping("/students")
@RestController
@CrossOrigin
public class StudentsController {
    @Autowired
    private StudentsService studentsService;
    @Autowired
    private UserrolesService userrolesService;
    @Autowired
    private UsersMapper usersMapper;
    /**
     * 全查
     *网络学生
     * @param students
     * @return
     */
    @GetMapping("/selectAllStudents")
    public Map<String, Object> selectAllStudents(Students students) {
        //查询登录的用户都有什么角色
        List<Userroles> userroles = userrolesService.selectUserrolesById(students.getUserId());
        for (Userroles u : userroles) {
            if (u.getName().equals("咨询经理")) {
                students.setNetpusherId(null);
                break;
            } else {
                students.setNetpusherId(students.getUserId());
            }
        }
        List<Students> studentsList = studentsService.selectAllByNetpusherIdAndIsValid(students);
        int count = studentsService.getCount(students);
        return LayUiResult.toClient("0", "成功", count, studentsList);
    }

    /**
     * 添加用户
     *
     * @param students 咨询师的id同样加到实体类里面
     * @return
     */
    @PostMapping("/createStudents")
    public Map<String, Object> createStudents(Students students) {
        Users users = usersMapper.selectById(students.getNetpusherId());
        students.setCreateUser(users.getLoginName());
        boolean rel = studentsService.save(students);
        return rel == true ? LayUiResult.toClient("0", "添加成功") : LayUiResult.toClient("1", "添加失败");
    }

    @DeleteMapping("/{id}")
    public Map<String, Object> deleteStudents(@PathVariable Integer id) {
        boolean rel = studentsService.removeById(id);
        return rel == true ? LayUiResult.toClient("0", "删除成功") : LayUiResult.toClient("1", "删除失败");
    }

    /**
     * 导出excel
     *网络学生
     * @param response
     * @param students
     */
    @GetMapping("/export")
    public void exportExcel(HttpServletResponse response, Students students) {
        //查询登录的用户都有什么角色
        List<Userroles> userroles = userrolesService.selectUserrolesById(students.getUserId());
        for (Userroles u : userroles) {
            if (u.getName().equals("咨询经理")) {
                students.setNetpusherId(null);
                break;
            } else {
                students.setNetpusherId(students.getUserId());
            }
        }
        List<Students_export> list = studentsService.exportStudents(students);
        ExcelUtil.export(response, "students", "students", list, Students_export.class);
    }

    /**
     * 导入excel
     *
     * @param file
     * @return
     */
    @PostMapping("/import")
    public Map<String, Object> importExcel(MultipartFile file,Integer userId,String loginName) {
        List<Students_import> importList = ExcelUtil.importExcel(file, Students_import.class, null);
        //把importList集合复制到另外一个集合（存的是member对象）
        List<Students> memberList = ObjectConversion.copy(importList, Students.class);
        for (Students s:memberList){
            s.setNetpusherId(userId);
            s.setCreateUser(loginName);
        }
        Boolean rel = studentsService.saveBatch(memberList);//执行保存
        Map<String, Object> rslmap = new HashMap<>();
        rslmap.put("code", rel ? "0" : "1");
        rslmap.put("msg", rel ? "导入成功" : "导入失败");
        return rslmap;
    }

    /**
     * 查询全部
     * 我的学生
     * @param students
     * @return
     */
    @GetMapping("/selectAllMyStudent")
    public Map<String,Object> selectAllMyStudent(Students students){
        //查询登录的用户都有什么角色
        List<Userroles> userroles = userrolesService.selectUserrolesById(students.getUserId());
        for (Userroles u : userroles) {
            if (u.getName().equals("咨询经理")) {
                students.setAskerId(null);
                break;
            } else {
                students.setAskerId(students.getUserId());
            }
        }
        List<Students> studentsList = studentsService.selectAllByIsValidAndAskerId(students);
        int count = studentsService.countStudent(students);
        return LayUiResult.toClient("0", "成功", count, studentsList);
    }
    /**
     * 导出excel
     *网络学生
     * @param response
     * @param students
     */
    @GetMapping("/exportMyStudent")
    public void exportMyStudent(HttpServletResponse response, Students students) {
        //查询登录的用户都有什么角色
        List<Userroles> userroles = userrolesService.selectUserrolesById(students.getUserId());
        for (Userroles u : userroles) {
            if (u.getName().equals("咨询经理")) {
                students.setAskerId(null);
                break;
            } else {
                students.setAskerId(students.getUserId());
            }
        }
        List<Students_export> list = studentsService.exportMyStudents(students);
        ExcelUtil.export(response, "students", "students", list, Students_export.class);
    }

    /**
     * 修改学生信息
     * @param students
     * @return
     */
    @PostMapping("/updateStudent")
    public Map<String,Object> updateStudent(Students students){
        boolean rsl = studentsService.updateById(students);
        return rsl == true?LayUiResult.toClient("0","修改成功"):LayUiResult.toClient("1","修改失败");
    }

    /**
     * 批量分配学生
     * @param ids 学生id
     * @param askerId 咨询师id
     * @param askerName 咨询师姓名
     * @return
     */
    @PostMapping("updateCounselor")
    public Map<String,Object> updateCounselor(@RequestParam List<Integer> ids,String askerId,String askerName){
        UpdateWrapper<Students> wrapper = new UpdateWrapper<>();
        wrapper.set("stuStatus",2).set("askerId",askerId).set("ziXunName",askerName)
                .in("id",ids);
        return studentsService.update(wrapper)?LayUiResult.toClient("0","分配成功"):LayUiResult.toClient("1","分配失败");
    }
    /**
     * 报表
     */
    @GetMapping("askerStudentReport")
    public List<Report> askerStudentReport(){
        return studentsService.askerStudentReport();
    }
    @GetMapping("netStudentReport")
    public List<Report> NetStudentReport() {
        return studentsService.netStudentReport();
    }
}
